package com.missfresh.cooperation2meituan.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;


public class HttpRaw {
	
	public static String postRaw(String url,String param){
		String result = "";
		try {
			CredentialsProvider provider = new BasicCredentialsProvider();
			UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("as_cashback", "YXNfY2FzaGJhY2s=");
			provider.setCredentials(AuthScope.ANY, credentials);
			HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
			HttpPost post = new HttpPost(url);
			StringEntity postingString = new StringEntity(param, "utf-8");// json传递
			postingString.setContentEncoding("UTF-8");
			postingString.setContentType("application/json");
			post.setEntity(postingString);
			post.setHeader("Content-type", "application/json;charset=UTF-8");
			HttpResponse response = httpClient.execute(post);
			result = EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}  
	
	public static void main(String[] args) throws Exception{
		String url="http://ma.staging.missfresh.cn/open_api/v1/orders";
		String param = readFromFile(new File("e:\\json.txt"));
		String result = postRaw(url,param);
		Map<String, Object> map = JsonUtil.json2map(result);
		System.out.println(result);
		System.out.println(map.get("message"));
	}
	
	public static String readFromFile(File src) {
        try {
            BufferedReader bufferedReader = new BufferedReader(
            		new InputStreamReader(new FileInputStream(src),"GB2312"));
            StringBuilder stringBuilder = new StringBuilder();
            String content;
            while((content = bufferedReader.readLine() )!=null){
                stringBuilder.append(content);
            }
            return stringBuilder.toString();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

    }
}
